const mysql = require('mysql');
const { MySQL } = require('../../../Config');
const log = require("../SysLog/OutPut");

class Database {
    constructor() {
        this.connection = mysql.createConnection({
            host: MySQL.host,
            port: MySQL.port,
            user: MySQL.userName,
            password: MySQL.password,
            database: MySQL.database,
            debug: MySQL.debugOptions,
            multipleStatements: MySQL.multipleStatements
        });
    }

    query(sql, args) {
        return new Promise((resolve, reject) => {
            this.connection.query(sql, args, (err, rows) => {
                if (err) return reject(err);
                resolve(rows);
            });
        });
    }

    close() {
        return new Promise((resolve, reject) => {
            this.connection.end(err => {
                if (err) reject(err);
                resolve();
            });
        });
    }

    beginTransaction() {
        return new Promise((resolve, reject) => {
            this.connection.beginTransaction(err => {
                if (err) reject(err);
                resolve();
            });
        });
    }

    commit() {
        return new Promise((resolve, reject) => {
            this.connection.commit(err => {
                if (err) return reject(err)
                resolve();
            });
        });
    }

    rollback() {
        return new Promise((resolve, reject) => {
            this.connection.rollback(err => {
                if (err) reject(err);
                resolve();
            });
        });
    }
}

module.exports = Database;